package org.rcy.ruicingmarket.common.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/10/24 17:41
 */


public class AESUtils {


	/**
	 * 加密算法
	 * @param oristr
	 * @param key
	 * @return
	 */
	public static final String encrypt(String oristr,String key) {
		Key secretKey = getKey(key);
		try {
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			byte[] p = oristr.getBytes("UTF-8");
			byte[] result = cipher.doFinal(p);
			BASE64Encoder encoder = new BASE64Encoder();
			String encoded = encoder.encode(result);
			return encoded;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


	/**
	 * 解密算法
	 * @param cipherText
	 * @param key
	 * @return
	 */
	public static final String decrypt(String cipherText,String key) {
		Key secretKey = getKey(key);
		try {
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] c = decoder.decodeBuffer(cipherText);
			byte[] result = cipher.doFinal(c);
			String plainText = new String(result, "UTF-8");
			return plainText;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


	private static Key getKey(String keySeed) {
		if (keySeed == null) {
			keySeed = System.getenv("AES_SYS_KEY");
		}
		if (keySeed == null) {
			keySeed = System.getProperty("AES_SYS_KEY");
		}
		if (keySeed == null || keySeed.trim().length() == 0) {
			keySeed = "abcd1234!@#$";// 默认种子
		}
		try {
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(keySeed.getBytes());
			KeyGenerator generator = KeyGenerator.getInstance("AES");
			generator.init(secureRandom);
			return generator.generateKey();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
